import os
import sys
from datetime import datetime
import logging

# 配置日志
# logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger('Program Name-Version')
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(levelname)s - Logger for YJQ : %(message)s')

consoleHeader = logging.StreamHandler()
consoleHeader.setFormatter(formatter)
consoleHeader.setLevel(logging.INFO)

logger.addHandler(consoleHeader)

def get_current_time():
    return datetime.now().strftime("%Y_%m_%d___%H_%M_%S")

def hex_to_bin(hex_file, path):
    with open(hex_file, 'r') as f:
        lines = f.readlines()

    data = []
    for line in lines:
        if line.startswith(':'):
            line = line.strip()
            data += [int(line[i:i+2], 16) for i in range(1, len(line), 2)]

    # 获取文件名（不包括后缀）
    file_name_without_extension = os.path.splitext(os.path.basename(hex_file))[0]
    bin_file = os.path.join(path, file_name_without_extension + '.bin')
    bin_file_date = os.path.join(path, file_name_without_extension + '_' + get_current_time() + '.bin')

    with open(bin_file, 'wb') as f:
        f.write(bytearray(data))
    with open(bin_file_date, 'wb') as f:
        f.write(bytearray(data))

    print(f'Hex file "{hex_file}" converted to bin files "{bin_file}" and "{bin_file_date}".')
    logger.info(f'Hex file "{hex_file}" converted to bin files "{bin_file}" and "{bin_file_date}".')
    logger.info("Bin文件生成成功！")
    logger.info(f"生成时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

# 遍历当前文件夹下hex文件
def traverse_hex_files(folder_path):
    extension = '.hex'

    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        if os.path.isfile(file_path) and filename.endswith(extension):
            print(filename.split('.')[0])
            logger.info(filename.split('.')[0])
            return file_path
    print(f'No hex files found in folder "{folder_path}".')
    logger.info(f'No hex files found in folder "{folder_path}".')
    return None

if __name__ == '__main__':
    # 获取当前脚本所在的目录
    if getattr(sys, 'frozen', False):
        # 如果程序是冻结的（即生成的 .exe 文件），获取可执行文件所在的目录
        current_folder = os.path.dirname(os.path.abspath(sys.executable))
    else:
        # 如果程序是脚本，获取脚本所在的目录
        current_folder = os.path.dirname(os.path.abspath(__file__))

    # 路径
    path = os.path.join(current_folder, 'BINOUT', get_current_time())


    hex_file = traverse_hex_files(current_folder)

    if hex_file is not None:
        # 创建输出文件夹
        os.makedirs(path, exist_ok=True)
        hex_to_bin(hex_file, path)
    else:
        print("No hex file to process.")
        logger.info("No hex file to process.")

    # 暂停命令窗口
    # input("Press Enter to exit...")